// @ts-ignore
import WEBSOCKET_API from "./websocketapi/localsense_ws";
// @ts-ignore
import { salt_en_val } from "./js/tool/aes/salt_config";
// @ts-ignore
import { logWithTime } from "./js/common";

enum CB_TYPE {
  AOA_POS = "onRecvAoAPos",
  SWITCH_AREA = "onAreaSwitch",
  ON_OPEN = "onOpen",
  ON_CLOSE = "onClose",
  ON_WS_CLOSE = "onWsClose",
  ON_ERROR = "onError",
  ON_WS_ERROR = "onWsError",
}

class AOA_Controller {
  tagId: string = "";
  m_work_as_worker = true;
  isInAoA = false;
  currentAOAPoint = { x: 0, y: 0 };
  currentFengMapPoint = { x: 0, y: 0 };
  moveTimeMills = 0;
  warnTimeMills = 0;
  MOVE_INTERVAL = 200; //单位：ms,间隔触发移动，避免消息过多

  constructor() {}

  error(callback) {
    WEBSOCKET_API.RegisterCallbackFunc("onError", (obj) => {
      console.log("AOA ws_api 连接错误", obj);
      callback(obj);
    });
  }

  onOpen(callback) {
    WEBSOCKET_API.RegisterCallbackFunc("onOpen", (obj) => {
      console.log("AOA ws_api 开启", obj);
      callback(obj);
    });
  }

  onClose(callback) {
    WEBSOCKET_API.RegisterCallbackFunc("onClose", (obj) => {
      console.log("AOA ws_api 关闭", obj);
      callback(obj);
    });
  }

  startPosition(mobileTagId) {
    this.tagId = mobileTagId;
    //AoA websocket开启
    WEBSOCKET_API.RejectBasicInfo();
    console.log("AOA WS Start Connect...");
    // var url = '10.1.41.119:48300';
    var url = "socket.zenosh.com:8282";

    WEBSOCKET_API.SetAccount(salt_en_val);
    WEBSOCKET_API.ClearBuffer();
    console.log(
      "AOA SDK VERSION  " +
        WEBSOCKET_API.getVersionMajor() +
        "." +
        WEBSOCKET_API.getVersionMinor()
    );
    console.log("Connect AOA tagId", this.tagId);
    setInterval(this.timeInvertTick, 10);
    // WEBSOCKET_API.RequireBasicInfo(url);
    // WEBSOCKET_API.RequireExtraInfo(url);
    // WEBSOCKET_API.RequireControlInfo(url);
    WEBSOCKET_API.setTag64CheckedFlag(true);
    WEBSOCKET_API.setPosOutType("XY");
  }

  stopPosition() {
    WEBSOCKET_API.RejectBasicInfo();
    WEBSOCKET_API.RejectExtraInfo();
    WEBSOCKET_API.RejectControlInfo();
  }

  onAOAPostion(callback) {
    if (this.isInAoA) {
      this.currentFengMapPoint = this.ConvertLocation(this.currentAOAPoint);
      callback(this.currentFengMapPoint);
    }
  }

  onRecvTagPos(callback) {
    //点名数据，修改数据，人员信息等数据，如下：
    WEBSOCKET_API.RegisterCallbackFunc("onRecvTagPos", (posObj: any) => {
      console.log("onRecvTagPos接收到点位数据", posObj);
      var tagVal = posObj[this.tagId];
      //判断定位消息是否为当前标签
      if (tagVal && tagVal.id == this.tagId) {
        //获取该用户实时坐标，当前坐标和上一个坐标相同
        if (
          this.currentAOAPoint.x === tagVal.x &&
          this.currentAOAPoint.y === tagVal.y
        )
          return;
        // 延时处理
        if (this.moveTimeMills > 0) return;
        this.moveTimeMills = this.MOVE_INTERVAL;
        this.currentAOAPoint = { x: tagVal.x, y: tagVal.y };
        console.log("currentAOAPoint", this.currentAOAPoint);
        logWithTime(
          "AOA POINT" +
            "-" +
            this.currentAOAPoint.x +
            "," +
            this.currentAOAPoint.y
        );
      } else {
        console.log("未匹配到当前标签", tagVal.id);
        return;
      }
    });
  }

  onAreaChange(callback) {
    //触发AOA区域切换判断
    if (!this.isInAoA) {
      var isEnteringAoA = this.isPointInEnterArea(this.currentAOAPoint);
      logWithTime("isEnteringAoA:" + isEnteringAoA);
      if (isEnteringAoA) {
        logWithTime("切换到AOA区域【触发进入AOA区域】" + isEnteringAoA);
        this.isInAoA = true;
        callback();
      }
    } else {
      var isLeavingAoA = !this.isPointInLeaveArea(this.currentAOAPoint);
      logWithTime("isLeavingAoA:" + isLeavingAoA);
      if (isLeavingAoA) {
        logWithTime("切换到FengMap区域【触发离开AOA区域】" + isLeavingAoA);
        this.isInAoA = false;
        callback();
      }
    }
  }

  timeInvertTick() {
    if (this.moveTimeMills > 0) {
      this.moveTimeMills -= 10;
    }
    if (this.warnTimeMills > 0) {
      this.warnTimeMills -= 10;
    }
    if (this.moveTimeMills < 0) {
      this.moveTimeMills = 0;
    }
    if (this.warnTimeMills < 0) {
      this.warnTimeMills = 0;
    }
  }

  //判断点是否包含在区域中（进入时使用）
  isPointInEnterArea(point) {
    var minX = 5377;
    var minY = 4550;
    var maxX = 6750;
    var maxY = 6895.3;
    return point.x > minX && point.x < maxX && point.y > minY && point.y < maxY;

    const center = {
      x: 6036.2,
      y: 5697.7,
    };
    // @ts-ignore
    return fengmap.FMCalculator.isContain(
      // @ts-ignore
      fengmap.FMCalculator.rectangleBuilder(1196, 2199.2, center),
      { x: point.x, y: point.y }
    );
  }

  //判断点是否包含在区域中（离开时使用）
  isPointInLeaveArea(point) {
    var minX = 5347;
    var minY = 4520;
    var maxX = 6780;
    var maxY = 6915.3;
    return point.x > minX && point.x < maxX && point.y > minY && point.y < maxY;
    const center = {
      x: 6036.2,
      y: 5697.7,
    };
    // @ts-ignore
    return fengmap.FMCalculator.isContain(
      // @ts-ignore
      fengmap.FMCalculator.rectangleBuilder(1212, 2215.2, center),
      { x: point.x, y: point.y }
    );
  }

  //定位坐标转换地图坐标
  ConvertLocation(coords) {
    //AOA坐标
    var origon = [
      //X 轴 间隔1米
      { x: 5470, y: 6866 }, //原点
      { x: 6664, y: 6814 }, //X轴终点
      { x: 5404, y: 4564 }, //y轴终点
    ];

    //fengmap坐标
    var target = [
      //X 轴 间隔1米
      { x: 13530083.581769802, y: 3661644.5113 },
      { x: 13530094.357336741, y: 3661637.2431 },
      { x: 13530070.848291438, y: 3661625.6331 },
    ];
    // @ts-ignore
    var coordsTransformer = new fengmap.FMCoordsTransformer({
      origon: origon,
      target: target,
    });
    var convertResult = coordsTransformer.transform(coords);
    //console.log(time_str + 'convertResult', convertResult)
    return convertResult;
  }
}

export default new AOA_Controller();
